<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StudentHub - 标签文章</title>
    <link rel="shortcut icon" href="/public/favicon.ico" type="image/x-icon">
    <link rel="shortcut icon" href="/public/favicon.ico" type="image/x-icon">
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 jQuery -->
    <script src="/jquery-3.7.1.min.js"></script>

    <!-- 配置 Tailwind (Assuming the same config as home.html) -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36D399',
                        neutral: {
                            100: '#F8FAFC',
                            200: '#E2E8F0',
                            300: '#CBD5E1',
                            400: '#94A3B8',
                            500: '#64748B',
                            600: '#475569',
                            700: '#334155',
                            800: '#1E293B',
                            900: '#0F172A',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.03)',
                        'card-hover': '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
                    }
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-balance {
                text-wrap: balance;
            }
            .animate-fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            .animate-slide-up {
                animation: slideUp 0.5s ease-out;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
    </style>

</head>
<body class="font-inter bg-neutral-100 text-neutral-800">

    <!-- Session Check and Page Content Wrapper -->
    <script>
        // Check for user ID in sessionStorage before loading the page
        // const userId = sessionStorage.getItem('userId');
        // if (!userId) {
        //     // If userId is not found, redirect to login page
        //     window.location.href = '/login.html';
        // } else {
        //     // If userId exists, show the page content
        //     document.body.classList.remove('hidden'); // Assume body is hidden by default if not authenticated
        // }
    </script>
    <!-- Optional: add a class="hidden" to body if you want to hide it until authenticated -->

    <!-- 导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-sm transition-all duration-300" id="navbar">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <a href="/qian/home.html" class="text-primary font-bold text-xl flex items-center">
                    <i class="fa fa-graduation-cap mr-2"></i>
                    <span>StudentHub</span>
                </a>
            </div>

            <nav class="hidden md:flex items-center space-x-6">
                <a href="/qian/home.html" class="text-primary font-medium">首页</a>
                <!-- 后台管理按钮 -->
                <a href="/hou/index.html" id="adminButton" class="hidden bg-primary text-white px-3 py-1 rounded font-medium hover:bg-primary/90 transition-colors">
                    后台管理
                </a>
            </nav>

            <div class="flex items-center space-x-4">
                <!-- Logout Button -->
                <button id="logoutButton" class="text-red-500 hover:text-red-700 transition-colors font-medium hidden md:block">
                    退出登录
                </button>

                <div class="relative hidden md:block">
                    <label>
                        <input type="text" placeholder="搜索课程、学习资料..." class="pl-10 pr-4 py-2 rounded-full bg-neutral-100 focus:outline-none focus:ring-2 focus:ring-primary/30 transition-all w-48 focus:w-64">
                    </label>
                    <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400"></i>
                </div>

                <div class="relative group">
                    <a href="/qian/user-center.html" class="w-4 h-4 rounded-full overflow-hidden border-2 border-white hover:border-primary transition-all">
                        <!-- Server-side code should replace the src with the user's avatar from session -->
                        <img src="https://picsum.photos/id/64/200/200" alt="用户头像" class="w-full h-full object-cover rounded-full" style="width: 40px; height: 40px;">
                    </a>

                    <div class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-2 z-10 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 transform group-hover:translate-y-0 translate-y-2">
                        <a href="user.html" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                            <i class="fa fa-user-o mr-2"></i> 个人主页
                        </a>
                        <a href="#" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                            <i class="fa fa-cog mr-2"></i> 设置
                        </a>
                        <div class="border-t border-neutral-200 my-1"></div>
                    </div>
                </div>

                <button class="md:hidden text-neutral-600 hover:text-primary transition-colors">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-8 md:py-12">
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8 w-full md:max-w-3xl lg:max-w-4xl mx-auto">
            <h1 class="text-xl md:text-2xl font-bold text-neutral-900 mb-6">
                标签文章: <span id="tagNameDisplay"></span>
            </h1>
            <div id="articlesList" class="space-y-4">
                <!-- 文章列表将在这里加载 -->
                <p class="text-center text-neutral-500">正在加载文章...</p>
            </div>
        </div>
    </main>

    <!-- 底部区域 -->
    <footer class="bg-white border-t border-neutral-200 mt-12">
        <div class="container mx-auto px-4 py-8">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
                <div>
                    <h3 class="text-lg font-bold text-neutral-900 mb-4">StudentHub</h3>
                    <p class="text-neutral-600 text-sm mb-4">探索知识，提升能力，与优秀学子共同成长。</p>
                    <div class="flex space-x-4">
                        <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                            <i class="fa fa-github text-xl"></i>
                        </a>
                        <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                            <i class="fa fa-twitter text-xl"></i>
                        </a>
                        <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                            <i class="fa fa-linkedin text-xl"></i>
                        </a>
                        <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                            <i class="fa fa-weibo text-xl"></i>
                        </a>
                    </div>
                </div>
            </div>

            <div class="border-t border-neutral-200 mt-8 pt-8 text-center text-neutral-500 text-sm">
                
            </div>
        </div>
    </footer>

    <!-- 返回顶部按钮 (Optional, include if needed) -->
    <!-- <button id="backToTop" class="fixed bottom-6 right-6 bg-primary/90 hover:bg-primary text-white w-12 h-12 rounded-full flex items-center justify-center shadow-lg transition-all transform translate-y-20 opacity-0">
        <i class="fa fa-angle-up text-xl"></i>
    </button> -->

    <script>
        $(document).ready(function() {
            // Dynamically set the header avatar from sessionStorage
            const userAvatarName = sessionStorage.getItem('avatarUrl'); // Get the avatar filename from sessionStorage using the key 'avatarUrl'
            const headerAvatar = $('#navbar a.rounded-full img'); // Corrected selector for the avatar image in the header
            const avatarBaseUrl = 'http://localhost:8082/upload/';
            if (userAvatarName && headerAvatar.length > 0) {
                headerAvatar.attr('src', avatarBaseUrl + userAvatarName);
            } else {
                // Optionally set a default avatar if not found in session
                headerAvatar.attr('src', 'http://localhost:8082/upload/default.jpg');
            }

            // Control visibility of Admin button based on user role
            const userRole = sessionStorage.getItem('userRole'); // Assuming user role is stored under this key
            const adminButton = $('#adminButton');

            if (userRole === 'ADMIN') {
                adminButton.removeClass('hidden');
            } else {
                adminButton.addClass('hidden');
            }

            // Function to get URL parameters
            function getUrlParameter(name) {
                name = name.replace(/[[\]]/g, '\\$&');
                const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
                const results = regex.exec(window.location.href);
                if (!results) return null;
                if (!results[2]) return '';
                return decodeURIComponent(results[2].replace(/\+/g, ' '));
            }

            // Get the tag name from the URL
            const tagName = getUrlParameter('tag');
            const tagNameDisplay = document.getElementById('tagNameDisplay');
            const articlesListContainer = $('#articlesList');

            if (tagName) {
                // Display the tag name
                tagNameDisplay.textContent = `#${tagName}`;

                // Function to format time ago (Copied from home.html)
                function timeAgo(timestamp) {
                    const now = new Date();
                    const past = new Date(timestamp);
                    const diffInSeconds = Math.floor((now - past) / 1000);

                    if (diffInSeconds < 60) {
                        return diffInSeconds + ' 秒前';
                    } else if (diffInSeconds < 3600) {
                        return Math.floor(diffInSeconds / 60) + ' 分钟前';
                    } else if (diffInSeconds < 86400) {
                        return Math.floor(diffInSeconds / 3600) + ' 小时前';
                    } else if (diffInSeconds < 2592000) { // 30 days
                        return Math.floor(diffInSeconds / 86400) + ' 天前';
                    } else if (diffInSeconds < 31536000) { // 365 days
                        return Math.floor(diffInSeconds / 2592000) + ' 个月前';
                    } else {
                        return Math.floor(diffInSeconds / 31536000) + ' 年前';
                    }
                }

                // Fetch articles by tag
                $.ajax({
                    url: `http://localhost:8082/api/articles/list?tagName=${encodeURIComponent(tagName)}`, // Assuming this endpoint exists or adapting fetchArticles logic
                    type: 'GET',
                    success: function(response) {
                        articlesListContainer.empty(); // Clear loading message
                        if (Array.isArray(response) && response.length > 0) {
                            const articles = response;
                            const avatarBaseUrl = 'http://localhost:8082/upload/';

                            articles.forEach(article => {
                                const articleHtml = `
                                    <div class="border-b border-neutral-100 pb-4">
                                        <div class="flex items-start">
                                            <img src="${avatarBaseUrl}${article.avatarUrl || 'default.jpg'}" alt="用户头像" class="w-10 h-10 rounded-full mr-3 object-cover">
                                            <div class="flex-1">
                                                <div class="flex justify-between">
                                                    <h3 class="font-medium text-neutral-900">${article.nickName || '匿名用户'}</h3>
                                                    <span class="text-xs text-neutral-500">${timeAgo(article.createdAt)}</span>
                                                </div>
                                                <a href="/qian/article_detail.html?articleId=${article.articleId}" class="block mt-1 text-neutral-800 hover:text-primary transition-colors">
                                                    <h4 class="font-bold">${article.title}</h4>
                                                </a>
                                                <p class="text-neutral-600 text-sm mt-1 line-clamp-2">${article.content || '无内容'}</p>

                                                <div class="flex items-center justify-between mt-2">
                                                    <div class="flex items-center space-x-4">
                                                        <button class="text-neutral-500 hover:text-primary transition-colors text-sm flex items-center">
                                                            <i class="fa fa-thumbs-o-up mr-1"></i> ${article.likes || 0} <!-- Assuming likes field -->
                                                        </button>
                                                        <button class="text-neutral-500 hover:text-primary transition-colors text-sm flex items-center">
                                                            <i class="fa fa-comment-o mr-1"></i> ${article.comments || 0} <!-- Assuming comments field -->
                                                        </button>
                                                        <button class="text-neutral-500 hover:text-primary transition-colors text-sm flex items-center">
                                                            <i class="fa fa-bookmark-o mr-1"></i> 收藏
                                                        </button>
                                                    </div>
                                                    <div class="flex items-center space-x-2">
                                                         ${article.tagName ? `<span class="bg-primary/10 text-primary px-2 py-0.5 rounded-full text-xs">${article.tagName}</span>` : ''}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                `;
                                articlesListContainer.append(articleHtml);
                            });

                        } else if (Array.isArray(response) && response.length === 0) {
                            articlesListContainer.html('<p class="text-center text-neutral-500">该标签下暂无文章。</p>');
                        } else {
                             console.error('获取标签文章失败: 响应格式不正确', response);
                             articlesListContainer.html('<p class="text-center text-red-500">加载文章失败，请稍后重试。</p>');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('标签文章请求失败:', error);
                        articlesListContainer.html('<p class="text-center text-red-500">加载文章失败，请稍后重试。</p>');
                    }
                });

            } else {
                // Handle case where tag parameter is missing
                 tagNameDisplay.textContent = '无效标签';
                articlesListContainer.html('<p class="text-center text-red-500">未指定标签。</p>');
            }

             // Logout button handler (Copied from home.html)
             $('#logoutButton').on('click', function(e) {
                 e.preventDefault(); // Prevent default link behavior
                 // Clear session storage
                 sessionStorage.removeItem('userId');
                 sessionStorage.removeItem('username'); // Assuming username is also stored
                 sessionStorage.removeItem('avatarUrl');
                 sessionStorage.removeItem('userRole'); // Assuming role is also stored

                 // Redirect to login page
                 window.location.href = '/login.html';
             });

        });
    </script>

</body>
</html> 